package com.voler.patchupdate

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContract
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import com.voler.bsdiffpatch.DiffPatchUtil
import com.voler.patchupdate.databinding.ActivityMainBinding
import java.io.File


class MainActivity : AppCompatActivity() {
    private var binding: ActivityMainBinding? = null
    private var registerForActivityResult: ActivityResultLauncher<Any>? = null

    override
    fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding!!.root)

        registerForActivityResult =
            registerForActivityResult(object : ActivityResultContract<Any, Uri?>() {
                override fun createIntent(context: Context, input: Any?): Intent {
                    val intent = Intent(Intent.ACTION_GET_CONTENT)
                    intent.type = "*/*"
                    return intent
                }

                override fun parseResult(resultCode: Int, intent: Intent?): Uri? {
                    return intent?.data
                }
            }) {
                it ?: return@registerForActivityResult
                val out = getExternalFilesDir("apk")
                val patch = File(out, "patch")
                val app = File(out, "app.apk")
                contentResolver.openInputStream(it)!!.copyTo(patch.outputStream())
                DiffPatchUtil.patch(
                    applicationInfo.sourceDir,
                    app.absolutePath,
                    patch.absolutePath
                )
                install(app)
            }
    }

    fun doPatch(view: View?) {
        registerForActivityResult?.launch("")
    }

    private fun install(newFile: File) {
        val intent = Intent(Intent.ACTION_VIEW)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            val apkUri = FileProvider.getUriForFile(this, "$packageName.fileProvider", newFile)
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive")
        } else {
            intent.setDataAndType(Uri.fromFile(newFile), "application/vnd.android.package-archive")
        }
        startActivity(intent)
    }
}